package com.thinkingcoder.tccache.server;

import org.springframework.stereotype.Component;

import com.thinkingcoder.tccache.TcPlugin;
import com.thinkingcoder.tccache.core.TcCache;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

@Component
public class TcCacheServer implements TcPlugin {

    public final static int DEFAULT_PORT = 6379;
    private int port;

    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    Channel channel;

    final TcCache cache = new TcCache();

    public TcCacheServer() {
        this(DEFAULT_PORT);
    }

    public TcCacheServer(int port) {
        this.port = port;
    }

    @Override
    public void init() {
        bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("redis-boss"));
        workerGroup = new NioEventLoopGroup(16, new DefaultThreadFactory("redis-worker"));
    }

    @Override
    public void startup() {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.SO_RCVBUF, 32 * 1024).childOption(ChannelOption.SO_SNDBUF, 32 * 1024)
                .childOption(EpollChannelOption.SO_REUSEPORT, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 写入时解码
                        socketChannel.pipeline().addLast(new TcCacheDecoder());
                        socketChannel.pipeline().addLast(new TcChannelHolder());
                        // 加入自定义Handler
                        socketChannel.pipeline().addLast(new TcCacheHandler());
                    }
                });

            channel = bootstrap.bind(port).sync().channel();
            System.out.println("开启netty redis服务器，端口为 " + port);
            this.cache.start();
            channel.closeFuture().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Override
    public void shutdown() {
        this.cache.shutdown();
        shutdownServerChannel();
        shutdownGracefully();
    }

    private void shutdownServerChannel() {
        if (this.channel != null) {
            this.channel.close();
            this.channel = null;
        }
    }

    private void shutdownGracefully() {
        if (this.bossGroup != null) {
            this.bossGroup.shutdownGracefully();
            this.bossGroup = null;
        }
        if (this.workerGroup != null) {
            this.workerGroup.shutdownGracefully();
            this.workerGroup = null;
        }
    }
}
